package com.read.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.read.common.annotation.UserLoginToken;
import com.read.common.response.RespEnum;
import com.read.common.response.RespResult;
import com.read.util.JwtUtil;
import com.read.util.RespUtil;
import com.read.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author sh-sunb6
 * @description
 * @date 2019-01-11 15:17
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object object) throws Exception {

        if(!"OPTIONS".equals(httpServletRequest.getMethod())){

            // 如果不是映射到方法直接通过
            if(!(object instanceof HandlerMethod)){
                return true;
            }

            HandlerMethod handlerMethod=(HandlerMethod)object;
            Method method=handlerMethod.getMethod();

            //检查有没有需要用户权限的注解
            if (method.isAnnotationPresent(UserLoginToken.class)) {
                UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
                if (userLoginToken.required()) {
                    RespResult result = null;

                    String token = httpServletRequest.getHeader("Authorization");// 从 http 请求头中取出 token

                    if (!StringUtil.isNotEmpty(token)) {
                        token = httpServletRequest.getParameter("Authorization");
                    }

                    // 判断token是否为空
                    if (token == null) {
                        result = RespUtil.error(RespEnum.TOKEN_EMPTY);
                        logger.info(RespEnum.TOKEN_EMPTY.getMsg());
                    } else {
                        //验证token
                        if (!JwtUtil.checkToken(token)) {
                            result = RespUtil.error(RespEnum.TOKEN_FAILED);
                            logger.info(RespEnum.TOKEN_FAILED.getMsg());
                        }
                    }

                    if (null != result) {
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("application/json; charset=utf-8");
                        PrintWriter out = null;
                        try {
                            out = response.getWriter();
                            out.println(JSON.toJSONString(result));
                            out.flush();
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (null != out) {
                                out.close();
                            }
                        }

                        return false;
                    }
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
